package com.linshengjian.snowball.payment;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@EnableConfigurationProperties(PaymentProperties.class)
public class PaymentConfig {

    @Autowired
    private PaymentProperties properties;

    @Autowired
    private ApplicationContext context;

    @Bean
    public ServletRegistrationBean paymenttCallbackUrl() {

        List<String> urls = new ArrayList<>();
        for (Map.Entry<String, Class<? extends IPaymentHandler>> entry : properties.getType().entrySet()) {
            urls.add(properties.getCallbackUrl() + "/" + entry.getKey());
        }

        ServletRegistrationBean bean = new ServletRegistrationBean(new PaymentService(), urls.toArray(new String[urls.size()]));
        bean.setName("callbackUrl");

        return bean;
    }

    private class PaymentService extends HttpServlet {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

            String result = "";

            String key = new File(req.getServletPath()).getName();

            Class<? extends IPaymentHandler> handlerClass = properties.getType().get(key);

            IPaymentHandler handler = null;

            try{
                handler = context.getBean(handlerClass);
            } catch (NoSuchBeanDefinitionException e) {
                try {
                    handler = handlerClass.newInstance();
                } catch (Exception e1) {
                    log.error("支付方式：" + key + " Handler 错误", e1.getMessage());
                }
            }

            if (handler != null) {
                result = handler.callback(req, resp);
            }

            resp.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = resp.getWriter();
            writer.write(StringUtils.isEmpty(result) ? "" : result);
            writer.flush();
        }
    }
}
